package com.xywh.wanandroid.viewmodel

import com.xywh.wanandroid.MyApp
import com.xywh.wanandroid.R
import com.xywh.wanandroid.event.EventViewModel
import com.xywh.wanandroid.ext.requestCompose
import com.xywh.wanandroid.ext.showToastMsg
import com.xywh.wanandroid.network.apiService
import com.xywh.wanandroid.util.CacheUtil
import dagger.hilt.android.lifecycle.HiltViewModel
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import javax.inject.Inject

@HiltViewModel
class LoginComposeViewModel @Inject constructor() : BaseViewModel() {

    fun loginWanAndroid(
        username: String,
        password: String,
        updateMainScreenCollectListData: () -> Unit,
        navigateUp: () -> Unit
    ) {
        val context = MyApp.instance
        when {
            username.isEmpty() -> showToastMsg(context.getString(R.string.hint_username))
            password.isEmpty() -> showToastMsg(context.getString(R.string.hint_password))
            else ->
                requestCompose(
                    {
                        apiService.loginWanAndroid(
                            username, password
                        )
                    },
                    {
                        showToastMsg("登录成功")
                        EventViewModel.isLogin.value = true
                        CacheUtil.setUser(it)
                        updateMainScreenCollectListData.invoke()
                        navigateUp.invoke()
                    },
                    {
                        showToastMsg(it.errorMsg)
                    },
                    true,
                    context.getString(R.string.login_loading_tip)
                )

        }
    }


}